<template>
	<base-wrapper activeTabName="clockin">
		<view v-if="!userStore.userData.wxopenid">
			<up-alert type="warning" center :description="description"></up-alert>
		</view>
		<view class="clockIn">
			<!-- <view class="CI-title">打卡表 </view> -->
			<view class="valiableInfo">
				<up-form labelPosition="top" :model="uploadRecordInfo" :rules="rules" ref="clockInForm" labelWidth="100%">
					<up-form-item label="手机号" prop="phone" required>
						<up-input v-model="uploadRecordInfo.phone" placeholder="请输入内容"></up-input>
					</up-form-item>
					<up-form-item label="得物动态链接" prop="article_url" required>
						<up-input v-model="uploadRecordInfo.article_url" placeholder="请输入内容"></up-input>
					</up-form-item>
					<up-form-item label="当前粉丝数" prop="fans" required>
						<up-input v-model="uploadRecordInfo.fans" placeholder="请输入内容"></up-input>
					</up-form-item>
					<up-form-item label="说明" prop="send_remark">
						<up-input placeholder="请输入内容" v-model="uploadRecordInfo.send_remark"></up-input>
					</up-form-item>
					<up-form-item prop="image_urls">
						<view class="upimg-style">
							<span style="text-align: center">动态记录截图</span>
							<span style="text-align: center; font-weight: 300">最大10M/个，支持png、jpg格式</span>
							<view class="upl-s">
								<up-upload
									:fileList="register_imageList"
									@afterRead="readSelectedPicture"
									@delete="deletePicture"
									multiple
									:maxCount="3"
									:previewFullImage="true"
								></up-upload>
							</view>
						</view>
					</up-form-item>

					<view v-if="uploadRecordInfo.status === -1">
						<up-button type="primary" @click="submit({ revoke: true })">重新上传</up-button>
					</view>
					<view v-else>
						<up-button type="primary" @click="submit({ revoke: false })">提交记录</up-button>
					</view>
				</up-form>
			</view>

			<!-- 底部显示每日的打卡状态，
			status = -2 表示当天没有打卡(灰色)  
			status = -1 表示当天有打卡但是 撤回状态 (红色)
			status = 0 表示当天有打卡但是 审核状态 (橙色)
			status = 1 表示当天有打卡 通过状态 (绿色)
			-->
			<view v-if="userStore.userData.wxopenid" class="clockInForm">
				<view class="clockInForm-block" v-for="(item, index) in userMonthClockInStatusList" :key="index" @click="gotoClockInDetail(item)">
					<span class="statusColor" :class="statusColorEnum[item.status]">{{ index + 1 }}</span>
				</view>
			</view>
		</view>
	</base-wrapper>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import dayjs from 'dayjs';
import { getBase64FromLocalAsync } from '@/utils/getBase64Async.js';
import { uploadFileToOSS } from '@/utils/aliyOss.js';
import { exUploadImages } from '@/utils/uploadImages.js';
import { imageType } from '@/utils/enum.js';
import { uploadClockIn, uploadDateStatus, todayUploadInfo, againClockIn } from '@/api/upload.js';
import { useUserInfo } from '@/stores/userInfo.js';
import { onLoad } from '@dcloudio/uni-app';
import axios from 'axios';

const statusColorEnum = {
	'-2': 'colorGray', // 没有打卡 (灰色)
	'-1': 'colorRed', // 撤回状态 (红色)
	0: 'colorOrange', // 审核状态 (橙色)
	1: 'colorGreen', // 通过状态 (绿色)
};

const revokeData = ref();

const userStore = useUserInfo();

const description = '请登录后再使用打卡功能';

let uploadRecordInfo = ref({
	wxopenid: userStore.userData.wxopenid,
	wxid: userStore.userData.wxid,
	upload_time: '',
	phone: '',
	release_time: '',
	article_url: '',
	fans: 0,
	image_urls: [],
	send_remark: '',
	status: -2,
});

let userMonthClockInStatusList = ref([]);

onMounted(async () => {
	uni.showLoading({ title: '刷新数据中...', mask: true });
	await userStore.updateUserData(userStore.userData.wxopenid);
	uni.hideLoading();
	uni.showToast({ title: '刷新成功!', icon: 'success' });

	if (!userStore.todayClockIn.canUpload) {
		uni.showToast({ title: '今天已经打卡过!', icon: 'fail' });
	}

	if (userStore.userData.wxopenid) {
		getUserMonthClockInStatus();
		// datetimePickerRef.value.setFormatter(formatter);
	}
});

// 使用 ref 创建响应式引用
const clockInForm = ref(null);

let register_imageList = ref([]);

onLoad((option) => {
	//页面载入时判断是否 含有回撤打卡对象
	if (option.revokeData) {
		try {
			// 待重新编辑上传的打卡信息是被JSON序列化后存到跳转页面路由的地址里面，所以要解码并解析数据
			const decodedRevokeData = JSON.parse(decodeURIComponent(option.revokeData));
			const deepCopy = (obj) => JSON.parse(JSON.stringify(obj));
			console.log('decodedRevokeData', decodedRevokeData);

			// 使用nextTick确保DOM更新后再设置数据
			nextTick(() => {
				// 回显数据到表单
				// uploadRecordInfo.value = {
				//
				// 	phone: decodedRevokeData.phone || '',
				// 	article_url: decodedRevokeData.article_url || '',
				// 	fans: decodedRevokeData.fans || 0,
				// 	send_remark: decodedRevokeData.send_remark || '',
				// 	image_urls: decodedRevokeData.image_urls || [],
				// };
				uploadRecordInfo.value = deepCopy(decodedRevokeData);
				console.log('nextTick => uploadRecordInfo ', uploadRecordInfo);

				// 更新图片列表
				//register_imageList.value = (decodedRevokeData.image_urls || []).map((url) => ({ url }));
				decodedRevokeData.image_urls.forEach((element, index) => {
					register_imageList.value.push({
						url: element,
						size: 1,
						ossExist: true,
					});
				});
				console.log('回撤更新图片列表', register_imageList.value);

				// 延迟执行表单校验
				setTimeout(() => {
					clockInForm.value?.validate();
				}, 1500);
			});
		} catch (error) {
			uni.$u.toast('数据回显失败');
		}
	}
});

//获取用户当月打卡的详情列表
const getUserMonthClockInStatus = async () => {
	if (userStore.userData.wxopenid == null || userStore.userData.wxopenid === '') return;
	let result = await uploadDateStatus({ wxopenid: userStore.userData.wxopenid });
	console.log('用户当月打卡状态详情', result);
	if (result.success) {
		userMonthClockInStatusList.value = result.data;
	}
};

// 表单提交校验规则
const rules = {
	phone: [
		{
			required: true,
			message: '请输入手机号',
			trigger: ['blur', 'change'],
		},
		{
			// 自定义验证函数
			validator: (rule, value, callback) => {
				// 返回true表示校验通过，返回false表示不通过
				return uni.$u.test.mobile(value);
			},
			message: '请输入符合规则的手机号',
			// 触发器可以同时用blur和change
			trigger: ['blur'],
		},
	],
	article_url: [
		{
			required: true,
			message: '请输入动态日期',
			trigger: ['blur', 'change'],
		},
		{
			// 自定义验证函数
			validator: (rule, value, callback) => {
				// 返回true表示校验通过，返回false表示不通过
				return uni.$u.test.url(value);
			},
			message: '请输入正确的链接',
			// 触发器可以同时用blur和change
			trigger: ['blur'],
		},
	],
	fans: [
		{
			required: true,
			message: '请输入当前账号粉丝数',
			trigger: ['blur', 'change'],
		},
		{
			// 自定义验证函数
			validator: (rule, value, callback) => {
				// 返回true表示校验通过，返回false表示不通过
				console.log('probe fans value is : ', value);
				return uni.$u.test.digits(value);
			},
			message: '请输入整数',
			// 触发器可以同时用blur和change
			trigger: ['blur'],
		},
	],
	image_urls: [
		{
			type: 'array',
			required: true,
			message: '请添加截图',
			trigger: ['blur', 'change'],
		},
	],
};

// 删除图片回调
const deletePicture = (event) => {
	//uploadRecordInfo.value.image_urls.splice(event.index, 1);
	register_imageList.value.splice(event.index, 1);
};

// 选中的图片信息回调
const readSelectedPicture = async (event) => {
	try {
		console.log('选择图片回调事件参数event', event);
		/*
    事件event中含有对象
    url : 本地选中图片的url地址
    size : 选中图片的二进制长度
    index : ui选中的图片索引
     */

		//代码更改,选中图片时候并不进行上传 本地图片url本身即可显示，在用户点击打卡进入submit方法后再进行上传
		//避免云存储oss空间的浪费
		//let result = await exUploadImages(event.file[0].url, event.file[0].size, 0);
		//console.log("阿里oss上传文件后的路径结果",result);

		//uploadRecordInfo.value.image_urls.push(result);
		//register_imageList.value.push({ url: result });

		register_imageList.value.push({ url: event.file[0].url, size: event.file[0].size, ossExist: false });
		console.log('添加选中图片到 imageList', register_imageList.value);
	} catch (error) {
		console.error('上传失败:', error);
	}
};

const submit = async ({ revoke }) => {
	console.log('submit 当前模式是否是重传模式', revoke);

	uni.showLoading({
		title: '正在打卡中..',
		mask: true,
	});

	if (!userStore.todayClockIn.canUpload) {
		uni.hideLoading();
		uni.showToast({ title: '今天已经打卡过!', icon: 'fail' });
		return;
	}

	//如果用户没有登录清空数据
	if (!userStore.userData.wxopenid || userStore.userData.wxopenid === '') {
		uploadRecordInfo.value = {};
		uploadRecordInfo.value.release_time = '';
		register_imageList.value = [];
		return uni.$u.toast('请登录后再使用该功能');
	}

	//先上传图片数据
	try {
		uploadRecordInfo.value.image_urls = [];
		for (const element of register_imageList.value) {
			const index = register_imageList.value.indexOf(element);
			//ossExist : true
			if (!element.ossExist) {
				let uploadResultUrl = await exUploadImages(element.url, element.size, 0);
				uploadRecordInfo.value.image_urls.push(uploadResultUrl);
			} else {
				console.log('表示从撤回页面转存过来的数据已经在oss中存储了,所以直接跳过不进行上传!');
				uploadRecordInfo.value.image_urls.push(element.url);
			}
			console.log('上传图片进度 ' + (index + 1) + '/' + register_imageList.value.length);
		}
	} catch (error) {
		console.error('上传失败:', error);
		uni.hideLoading();
		uni.showToast({ title: '上传图片中断!', icon: 'fail' });
		return;
	}

	//再提交表单
	clockInForm.value
		.validate()
		.then(async (valid) => {
			if (valid) {
				if (!revoke) {
					uploadRecordInfo.value.upload_time = dayjs(new Date()).format('YYYY-MM-DDTHH:mm:ss');
					uploadRecordInfo.value.release_time = dayjs(new Date()).format('YYYY-MM-DDTHH:mm:ss');
				} else {
					uploadRecordInfo.value.upload_time = dayjs(Date.parse(uploadRecordInfo.value.upload_time)).format('YYYY-MM-DDTHH:mm:ss');
					uploadRecordInfo.value.release_time = dayjs(Date.parse(uploadRecordInfo.value.release_time)).format('YYYY-MM-DDTHH:mm:ss');
				}

				uploadRecordInfo.value.status = 0;

				//这里有个问题 明明 程序运行到这里的时候 uploadRecordInfo.value.image_urls 是有数据的,但是打印说是空数组
				//调用上传接口也是正常的
				console.log('开始提交数据', uploadRecordInfo.value);

				try {
					let result = !revoke ? await uploadClockIn(uploadRecordInfo.value) : await againClockIn(uploadRecordInfo.value);

					console.log('打卡返回报文', result);
					if (result.success) {
						uni.hideLoading();
						uploadRecordInfo.value = {};
						register_imageList.value = [];
						uni.$u.toast(result.message);
						getUserMonthClockInStatus(); //调用打卡接口成功后 重新获取用户的月打卡记录状态列表
						userStore.updateUserData(userStore.userData.wxopenid); //调用更新用户部分信息方法
						clockInForm.value?.resetFields(); //重置表单数据
					}
				} catch (e) {
					console.error('打卡出现了异常并且捕获到了...');
					uni.hideLoading();
					uploadRecordInfo.value = {};
					register_imageList.value = [];
				}
			} else {
				uni.hideLoading();
				uni.$u.toast('校验失败1');
			}
		})
		.catch(() => {
			uni.hideLoading();
			uni.$u.toast('校验失败2');
		});
};

const gotoClockInDetail = (e) => {
	uni.navigateTo({
		url: `clockInDesc?date=${JSON.stringify(e.date)}`,
	});
};
</script>

<style lang="scss" scoped>
.clockIn {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 20rpx;

	.CI-title {
		font-size: 40rpx;
		font-weight: 600;
	}
}

:deep(.u-upload__wrap.data-v-cafe0b2a) {
	justify-content: center;
}

.valiableInfo {
	width: 100%;

	.upimg-style {
		display: flex;
		justify-content: center;
		flex-wrap: wrap;
		flex-direction: column;

		.upl-s {
			padding: 20rpx 0;
		}
	}

	.yearMouthDayBox {
		width: 100%;
		height: 70rpx;
		display: flex;
		align-items: center;
		border: 1rpx solid #dadbde;
		border-radius: 4px;
		padding-left: 8px;
		color: #8a8b8e;
	}
}

.clockInForm {
	display: flex;
	justify-content: space-between;
	flex-wrap: wrap;
	width: 100%;
	margin: 10rpx 0;

	.clockInForm-block {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 100rpx;
		height: 100rpx;
		margin: 20rpx 0;
		border-radius: 10rpx;
		background-color: #bbbfc5;
		color: white;

		.statusColor {
			display: flex;
			align-items: center;
			justify-content: center;
			width: 100%;
			height: 100%;
			border-radius: 10rpx;
			// background-color: #18b566;
		}
	}

	.colorGray {
		background-color: gray;
	}

	.colorRed {
		background-color: red;
	}

	.colorOrange {
		background-color: orange;
	}

	.colorGreen {
		background-color: green;
	}
}
</style>
